﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_ProductController : MvcControllerBase
    {
        private WarehouseBLL bll = new WarehouseBLL();

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "物品首页", "Index")]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "物品详情", "Form")]
        public ActionResult Form()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "物品类型首页", "Form")]
        public ActionResult TypeIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "物品类型详情", "TypeForm")]
        public ActionResult TypeForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "入仓物品", "BillProductForm")]
        public ActionResult BillProductForm()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取物品列表信息
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "数据列表", "GetPageList")]
        public ActionResult GetPageList(Pagination pagination, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetProductInfoList().ToList();
            data = data.OrderByDescending(s => s.CreateDate).ToList();
            var query = bll.GetProductTypeList().ToList();
            if (!queryParam["ProductType"].IsEmpty() && queryParam["ProductType"].ToString() != "All")
            {
                query = query.Where(e => e.ParentId == queryParam["ProductType"].ToString()).ToList();
                if (query.Count() > 0)
                {
                    List<ProductInfoEntity> lst = new List<ProductInfoEntity>();
                    foreach (var item in query)
                    {
                        var data1 = data.Where(e => e.Type == item.Id);
                        foreach (var item1 in data1)
                        {
                            lst.Add(item1);
                        }
                    }
                    data = lst;
                }
                else
                {
                    data = data.Where(e => e.Type == queryParam["ProductType"].ToString()).ToList();
                }
            }
            if (!queryParam["keyword"].IsEmpty())
            {
                var condition = !queryParam["condition"].IsEmpty() ? queryParam["condition"].ToString() : "";
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    case "Brand":
                        data = data.Where(t => t.Brand.Contains(keyword)).ToList();
                        break;
                    case "ModelNo":
                        data = data.Where(t => t.ModelNo.Contains(keyword)).ToList();
                        break;
                    default:
                        data = data.Where(t => t.Code.Contains(keyword) || t.Name.Contains(keyword) || t.Brand.Contains(keyword) || t.ModelNo.Contains(keyword)).ToList();
                        break;
                }
            }
            foreach (ProductInfoEntity item in data)
            {

                var query1 = bll.GetProductTypeList().Where(e => e.Id == item.Type).FirstOrDefault();
                if (query1 == null)
                {
                    item.Type = "---";
                }
                else
                {
                    if (item.Type == "All")
                    {
                        item.Type = "---";
                    }
                    else
                    {
                        string AllName = "";
                        item.Type = GetAllName(item.Type, AllName);
                    }
                }
            }
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data.Skip((pagination.page - 1) * pagination.rows).Take(pagination.rows),
                total = Math.Ceiling(Convert.ToDouble(data.Count) / Convert.ToDouble(pagination.rows)),
                page = pagination.page,
                records = data.Count,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 获取物品信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取物品信息", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = bll.GetProductInfoEntity(keyValue);
            return Content(data.ToJson());
        }


        /// <summary>
        /// 获取物品类型树列表
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取物品类型树列表", "GetTypeTreeListJson")]
        public ActionResult GetTypeTreeListJson(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetProductTypeList().ToList();
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }
            }
            var TreeList = new List<TreeGridEntity>();
            foreach (ProductTypeEntity item in data)
            {
                TreeGridEntity tree = new TreeGridEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.parentId = item.ParentId.IsEmpty() ? "0" : item.ParentId;
                tree.expanded = true;
                tree.hasChildren = hasChildren;
                if (item.ParentId != "0")
                {
                    // item.ParentId = (((bll.GetProductTypeList()).Where(t => t.Id == item.ParentId)).FirstOrDefault()).Name.ToString();
                }
                else
                {
                    item.ParentId = "---";
                }
                tree.entityJson = item.ToJson();
                TreeList.Add(tree);

            }
            return Content(TreeList.TreeJson());
        }

        /// <summary>
        /// 获取物品类别树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取物品类别树", "GetTypeTreeJson")]
        public ActionResult GetTypeTreeJson()
        {
            var data = bll.GetProductTypeList().ToList();
            var treeList = new List<TreeEntity>();
            TreeEntity tree1 = new TreeEntity { id = "All", text = "所有物品", value = "All", parentId = "0", isexpand = true, complete = true, hasChildren = true };
            treeList.Add(tree1);
            foreach (ProductTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.ParentId) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.ParentId == "0" ? "All" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }

            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 获取类别实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取类别实体", "GetTypeFormJson")]
        public ActionResult GetTypeFormJson(string keyValue)
        {
            var data = bll.GetProductTypeEntity(keyValue);
            return Content(data.ToJson());
        }
        #endregion

        #region 保存数据
        /// <summary>
        /// 保存物品
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <returns></returns> 
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存物品", "SaveForm")]
        public ActionResult SaveForm(string keyValue, ProductInfoEntity entity)
        {
            var type = entity.Type;
            if (type == "All")
            {
                return Error("该类型不能作为物品类型！");
            }
            var data = bll.GetProductTypeList().Where(e => e.ParentId == type).ToList();
            try
            {
                if (data.Count() == 0)
                {
                    bll.SaveProductInfoForm(keyValue, entity);
                    return Success("操作成功。");
                }
                else
                {
                    return Error("只有最末级别类型，才能添加物品！");
                }

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }


        /// <summary>
        /// 删除物品
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "删除物品", "RemoveForm")]
        public ActionResult RemoveForm(string keyValue)
        {
            try
            {
                bll.RemoveProductForm(keyValue);
                return Success("删除成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        /// <summary>
        /// 保存物品类别
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <returns></returns> 
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存物品类别", "SaveTypeForm")]
        public ActionResult SaveTypeForm(string keyValue, ProductTypeEntity entity)
        {
            var ParentId = entity.ParentId;
            if (ParentId == "All")
            {
                return Error("所有物品不能作为上级类型使用!");
            }
            try
            {
                if (ParentId.IsEmpty())
                {
                    bll.SaveProductTypeForm(keyValue, entity);
                    return Success("操作成功。");
                }
                else
                {
                    var data = bll.GetProductInfoList().Where(e => e.Type == ParentId).ToList();
                    if (data.Count() == 0)
                    {
                        bll.SaveProductTypeForm(keyValue, entity);
                        return Success("操作成功。");
                    }
                    else
                    {
                        return Error("该父类挂有物品，不能作为上级父类！");
                    }
                }

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        /// <summary>
        /// 删除物品类别
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "删除物品类别", "RemoveTypeForm")]
        public ActionResult RemoveTypeForm(string keyValue)
        {
            var data = bll.GetProductTypeList().Where(e => e.ParentId == keyValue).ToList();
            var data1 = bll.GetProductInfoList().Where(e => e.Type == keyValue && e.EnabledMark == 1).ToList();
            if (data1.Count() > 0)
            {
                return Error("该类下挂有物品，无法删除！");
            }
            else
            {
                if (data.Count() == 0)
                {
                    try
                    {
                        bll.RemoveProductTypeForm(keyValue);
                        return Success("删除成功。");
                    }
                    catch (Exception e)
                    {
                        return Error(e.Message);
                    }
                }
                else
                {
                    return Error("请先删除其子节点！");
                }
            }
        }
        #endregion

        #region 其他
        /// 获得类型全名称
        /// </summary>
        /// <param name="Type">类型编号</param>
        /// <param name="AllName">类型全名称</param>
        /// <returns></returns>
        private string GetAllName(string Type, string AllName)
        {

            var data = bll.GetProductTypeList().ToList();
            data = data.Where(e => e.Id == Type).ToList();
            if (data.Count() == 0)
            {
                AllName = AllName.Substring(1);
                return AllName;
            }
            else
            {
                string s = "/" + data.FirstOrDefault().Name;
                AllName = s + AllName;
                Type = data.FirstOrDefault().ParentId;
                return GetAllName(Type, AllName);
            }

        }
        #endregion


    }
}
